package dc.sockettest;

import java.io.*;
import java.net.*;

public class EchoClient {

    public static void main(String[] args) throws Exception {
		String userInput = null;
		String echoMessage = null;
		BufferedReader stdIn = null;
		Socket socket = null;
		InputStream inStream = null;
		OutputStream outStream = null;
		BufferedReader in = null;
		PrintWriter out = null;

		try{
			stdIn = new BufferedReader(new InputStreamReader(System.in));

			//创建套接字
			socket = new Socket("127.0.0.1", 8189);
			System.out.println("Connected to Server");

			//建立连接
			inStream = socket.getInputStream();
			outStream = socket.getOutputStream();
			in = new BufferedReader(new InputStreamReader(inStream));
			out = new PrintWriter(outStream);

			//通信
			while((userInput=stdIn.readLine())!=null)
			{
				out.println(userInput);
				out.flush();
				echoMessage = in.readLine();
				System.out.println("Echo from server: " + echoMessage);
			}


		}catch (SocketException e){
			System.out.println("Error:\n"+e);
		}catch (IOException e){
			System.out.println("Error:\n"+e);
		}finally {
			try {
				//关闭IO和关闭socket
				if (out!=null)
					out.close();
				if (in!=null)
					in.close();
				if (outStream!=null)
					outStream.close();
				if (inStream!=null)
					inStream.close();
				if (stdIn!=null)
					stdIn.close();
				if (socket!=null)
					socket.close();
			}catch (Exception e){
				System.out.println("Error:"+e);
			}
		}
	}
}